import * as THREE from 'three'
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js'

const tagGroup = new THREE.Group()

const getMatchingValue = (data, name) => {
  for (const key in data) {
    if (name.includes(key)) {
      return data[key]
    }
  }
  return 0
}

const cleanCityName = name => {
  const removeStrings = [
    '维吾尔',
    '回族',
    '自治区',
    '特别行政区',
    '壮族',
    '省',
    '市'
  ]
  removeStrings.forEach(val => {
    if (name.includes(val)) {
      name = name.replace(val, '')
    }
  })
  return name
}

function createMapTag(cityData, waterObj) {
  cityData.forEach(item => {
    const tagDom = document.getElementById('mapTag').cloneNode(true)
    tagDom.style.display = 'block'
    tagDom.style.top = '-30px'
    tagDom.style.left = '0px'

    const result = getMatchingValue(waterObj, item.name)

    let valueElement = tagDom.querySelector('.value')
    let nameElement = tagDom.querySelector('.name')

    if (!valueElement) {
      valueElement = document.createElement('span')
      valueElement.className = 'value'
      tagDom.appendChild(valueElement)
    }

    if (!nameElement) {
      nameElement = document.createElement('span')
      nameElement.className = 'name'
      tagDom.appendChild(nameElement)
    }

    nameElement.innerHTML = `${cleanCityName(item.name)}`

    if (result !== 0) {
      valueElement.innerHTML = `  : ${result} 个`
      valueElement.style.display = 'inline'
    } else {
      valueElement.style.display = 'none'
    }

    const css2DObject = new CSS2DObject(tagDom)
    css2DObject.position.set(item.x, 0, -item.y)
    tagGroup.add(css2DObject)

    document.body.appendChild(tagDom)
  })
}

export { createMapTag, tagGroup }
